package alf.mapping.service.help;

import alf.common.data.DataException;
import alf.common.domain.AbstractDomainService;
import alf.common.domain.DomainException;
import alf.mapping.data.HelpLoader;
import alf.mapping.dto.help.Entry;
import alf.mapping.dto.help.Link;
import alf.mapping.view.Env;
import alf.mapping.view.activity.R;
import android.content.res.XmlResourceParser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import alf.mapping.dto.help.Category;
import android.nfc.tech.IsoDep;
import java.util.HashMap;

public class HelpService extends AbstractDomainService {
	private Map<String,Entry> helpMap; 
	private Map<String,Link[]> categoryMapCache;
	// Singleton
	private static HelpService instance;

	public static HelpService getInstance() {
		if (instance == null) {
			instance = new HelpService();
		}
		return instance;
	}
	private HelpService() {
		super();
	}

	public Entry getEntry(String id) throws DomainException {
		init();

		Entry e = helpMap.get(id);
		return e;
	}

	public Entry getEntry(Link k) throws DomainException {
		return getEntry(k.getRef());
	}

	public Link[] getCategoryEntrys(String name) throws DomainException {
		init();
		Link[] result = categoryMapCache.get(name);
		if (result == null) {
			List<Link> links = new ArrayList<Link>();
			Collection<Entry> entradas = helpMap.values();
			for (Entry e: entradas) {
				if (isOfCategory(e, name)) {
					links.add(new Link(e));
				}
			}
			if (links.size() > 0) {
				result =  links.toArray(new Link[1]);
				categoryMapCache.put(name, result);
			} 
		}
		return result;
	}

	private boolean isOfCategory(Entry e, String name) {
		if  (e != null && name != null && e.getCategorys() != null) {
			for (Category c: e.getCategorys()) {
				if (c!=null && name.equals(c.getName())) {
					return true;
				}
			}
		}
		return false;
	}
	private void init() throws DomainException {
		if (helpMap == null) {
			loadHelp();
			categoryMapCache = new HashMap<String,Link[]>();
		}
	}

	private void loadHelp() throws DomainException {
		XmlResourceParser p = Env.getResources().getXml(R.xml.help);
		HelpLoader hp = new HelpLoader();
		try {
			helpMap = hp.parse(p);
		} catch (DataException e) {
			encapulate("Data error", e);
		}
	}
}
